/*
 * Copyright 2010 Kevin L'Huillier <klhuillier@gmail.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.lhuillier.pwsafe.io;


import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import org.lhuillier.pwsafe.io.v3.V3DbReader;
import org.lhuillier.pwsafe.model.Database;
import com.google.inject.Inject;


class DbReaderImpl implements DbReader {
    private final V3DbReader v3Reader;

    @Inject
    DbReaderImpl(V3DbReader v3Reader) {
        this.v3Reader = v3Reader;
    }
    
    @Override
    public Database load(byte[] data, StretchedKey key) throws DbIoException {
        String tag = tag(data);
        
        if ("PWS3".equals(tag)) {
            return v3Reader.load(data, key);
        }
        
        throw corrupt();
    }

    @Override
    public RawDb loadRaw(byte[] data, StretchedKey key) throws DbIoException {
        String tag = tag(data);
        
        if ("PWS3".equals(tag)) {
            return v3Reader.loadRaw(data, key);
        }
        
        throw corrupt();
    }

    @Override
    public StretchedKey prepareKey(byte[] data, String password)
            throws DbIoException {
        String tag = tag(data);
        
        if ("PWS3".equals(tag)) {
            return v3Reader.stretchKey(data, password);
        }

        throw corrupt();
    }
    
    private String tag(byte[] data) {
        try {
            return new String(Arrays.copyOf(data, 4), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new AssertionError("UTF-8 is not available");
        }
    }

    private DbIoException corrupt() {
        return new DbIoException("The data either does not contain a "
                + "PasswordSafe password database, it is not a supported "
                + "version of PasswordSafe, or the database is corrupt.");
    }
}
